package com.coc.core.security.service;
import com.coc.entity.system.SysPermission;
import com.coc.entity.system.SysUser;
import com.coc.service.system.SysPermissionService;
import com.coc.service.system.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: songju
 * @Description:
 * @Date Create in 2020/8/29
 */
@Component
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysPermissionService sysPermissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (username == null || "".equals(username)) {
            throw new RuntimeException("用户不能为空");
        }
        //根据用户名查询用户
        SysUser sysUser = sysUserService.selectByName(username);
        if (sysUser == null) {
            throw new RuntimeException("用户不存在");
        }
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        if (sysUser != null) {
            //获取该用户所拥有的权限
            List<SysPermission> sysPermissions = sysPermissionService.selectListByUser(sysUser.getId());
            // 声明用户授权
            sysPermissions.forEach(sysPermission -> {
                if (sysPermission!=null){
                    GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(sysPermission.getCode());
                    grantedAuthorities.add(grantedAuthority);
                }
            });
        }
        return new User(sysUser.getUsername(), sysUser.getPassword(), sysUser.getIsDel().equals(0), sysUser.getNotExpired().equals(0), sysUser.getCredentialsNotExpired().equals(0), sysUser.getAccountNotLocked().equals(0), grantedAuthorities);
    }
}
